package com.aiolos.hadoop.mapreduce.wc;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Iterator;

/**
 * Reducer的输入是Map的输出,所以是Text, IntWritable
 * Reducer的输出也是Text, IntWritable
 */
public class WordCountReducer extends Reducer<Text, IntWritable,Text, IntWritable> {

    /**
     * map返回的格式是： (hello,1) (world,1)
     *                 (hello,1) (world,1)
     *                 (hello,1) (world,1)
     *                 (welcome,1)
     *
     * map的输出到reduce端，是按照相同的key分发到一个reduce上去执行(Shuffle的执行过程)
     * reduce1: (hello,1)  (hello,1)  (hello,1)  ===> (hello,<1,1,1>)
     * reduce2: (world,1) (world,1) (world,1) ===> (world,<1,1,1>)
     * reduce3:(welcome,1) ===> (welcome,<1>)
     *
     * reduce方法的参数：Text key, Iterable<IntWritable> values 就是 (hello,<1,1,1>)
     *
     * Mapper类和Reducer类中使用到模板的设计模式
     */
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        int count = 0;

        //1. 迭代求和：<1,1,1>
        Iterator<IntWritable> iterator = values.iterator();
        while (iterator.hasNext()){
            // count += 1
            IntWritable value = iterator.next();
            count += value.get();
        }
        //2. 将结果写到上下文，供后续组件处理
        context.write(key,new IntWritable(count));
    }
}
